package com.itcam.mongo.service.impl;

import com.itcam.mongo.domain.Person;
import com.itcam.mongo.service.PersonService;
import lombok.RequiredArgsConstructor;
import org.bson.types.ObjectId;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author : Cammy.Wu
 * Description : 
 */

@Service
public class PersonServiceImpl implements PersonService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void savePerson(Person person) {
        this.mongoTemplate.save(person);
    }

    /**
     * 根据传入的Person对象更新数据库中的记录。
     * 此方法会根据Person对象的id查询数据库，
     * 并将查询到的记录的age、name、location和address字段更新为Person对象的对应属性值。
     *
     * @param person 包含要更新信息的Person对象
     */
    @Override
    public void update(Person person) {
        /*
            db.persons.updateOne(
                { "id": <person_id> },
                {
                    $set: {
                        "age": <person_age>,
                        "name": "<person_name>",
                        "location": "<person_location>",
                        "address": "<person_address>"
                    }
                }
            )
         */

        // 创建一个查询对象，根据Person对象的id来查找要更新的记录
        Query query = Query.query(Criteria.where("id").is(person.getId()));

        // 创建一个更新对象，设置要更新的字段及其新值
        Update update = Update.update("age", person.getAge())
                // 设置name字段为Person对象的name属性值
                .set("name", person.getName())
                // 设置location字段为Person对象的location属性值
                .set("location", person.getLocation())
                // 设置address字段为Person对象的address属性值
                .set("address", person.getAddress());

        // 使用MongoTemplate执行更新操作，更新符合条件的第一条记录
        this.mongoTemplate.updateFirst(query, update, Person.class);
    }


    @Override
    public List<Person> queryPersonListByName(String name) {
        Query query = Query.query(Criteria.where("name").is(name));
        return this.mongoTemplate.find(query, Person.class);
    }

    @Override
    public List<Person> queryPersonPageList(int page, int pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        Query query = new Query().with(pageRequest);
        return this.mongoTemplate.find(query, Person.class);
    }

    @Override
    public void deleteById(String id) {
        Query query = Query.query(Criteria.where("id").is(new ObjectId(id)));
        this.mongoTemplate.remove(query, Person.class);
    }
}
